import wx
import os
from wx.richtext import RichTextCtrl
from wx.stc import StyledTextCtrl

class ScriptPreviewPanel(wx.Panel):
    """
    This class represents the script preview panel. It provides a preview of the 
    script test that is being created to the user.
    @author: Danilo Torres
    """
    
    LINE_SEPARATOR = os.linesep
    
    def __init__(self, parent, id):
         """
         Initializes this panel.
         """
         wx.Panel.__init__(self, parent, id, size=wx.Size(400, 300))
         self.SetBackgroundColour(wx.WHITE)
         self.sizer = wx.BoxSizer(wx.VERTICAL)
         self.initializePreview()
         self.SetSizer(self.sizer)
         self.SetAutoLayout(True)
         self.listeners = []
         
    def initializePreview(self):
        self.previewPanel = StyledTextCtrl(self, -1, size=wx.Size(400,300))
        self.previewPanel.SetScrollWidth(300)
        self.sizer.Add(self.previewPanel, 1, wx.EXPAND)
        self.previewPanel.Bind(wx.EVT_KEY_UP, self.onKeyUp)
         
    def onKeyUp(self, event):
        self.fireScriptModified()
         
    def addListener(self, listener):
        """
        Adds a listener to the Panel, whenever occurs 
        """
        self.listeners.append(listener)
        
    def fireScriptModified(self):
        for listener in self.listeners:
            listener.notifyScriptModified()
            
    def addScriptLine(self, line):
        """This method adds a new line to the script test and shows the change in
        the preview. """
        self.previewPanel.AppendText(line)
        self.addNewLine()
        self.fireScriptModified()

    def appendText(self, text):
        """
        Appends the text to the end of the script.
        """
        self.previewPanel.AppendText(text)
        self.fireScriptModified()
        
    def addNewLine(self):
        """
        Appends a LINE SEPARATOR to the end of the script.
        """
        self.previewPanel.AppendText(self.LINE_SEPARATOR)
        self.fireScriptModified()
        
    def clear(self):
        """
        Clears the content of the script.
        """
        if self.previewPanel != None:
            self.sizer.Remove(self.previewPanel)
            self.previewPanel.Destroy()
        self.initializePreview()
        self.previewPanel.ClearAll()
        self.fireScriptModified()
        
    def getText(self):
        """
        Returns the content of the script.
        """
        return self.previewPanel.GetText()